import React, { Component } from 'react'
import { Segmented, Tooltip, Button, Radio, } from 'antd';
import { Form, DatePicker, Select, InputNumber } from 'antd';
import { CaretRightOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'

import MeasurementTree from 'src/component/MeasurementTree'
import { TableType, PERIOD_OPTIONS, MODE_OPTIONS, STEP_INTERVAL_OPTIONS } from 'src/core/common'

import { EE } from 'src/ipc/sparkchannel'


/**
 * Plan Object as
 * {
 *   mode_type: 'GENERAL_CURVE',
 *   picker_type: 'DATE',
 *   data_interval: 5,
 *   interval_unit: 'MIN_UNIT',
 *   point_list: 'xxx,dddd',
 *   from: dayjs,
 *   to: dayjs,
 * }
 * 
 * measurement is
 *  [{
 *    "point_id": "r256:ai:0",
 *    "point_desc": "交流AB线电压",
 *    "point_type": 127,
 *    "station_desc": "郎山储能",
 *    "bay_desc": "#1PCS",
 *    "device_desc": "#1PCS",
 *  }, ...]
 */

function getPlanName(plan, measurements) {
  const point = measurements[0];
  let title = `${point.station_desc}/${point.bay_desc}/${point.device_desc}/${point.point_desc}`;
  if (measurements.length > 1) {
    title += `【等${measurements.length - 1}个量测】`;
  }

  const dateFmt = 'YYYYMMDD';
  if (plan.picker_type === 'DATE') {
    title += `${plan.from.format(dateFmt)}日曲线`;
  } else if (plan.picker_type === 'RANGE') {
    title += `${plan.from.format(dateFmt)}-${plan.to.subtract(1, 'day').format(dateFmt)}多日曲线`;
  } else if (plan.picker_type === 'COMPRANGE') {
    title += `${plan.from.format(dateFmt)}-${plan.to.subtract(1, 'day').format(dateFmt)}多日对照曲线`;
  }

  const mode = MODE_OPTIONS.find(op => op.value === plan.mode_type);
  title += '/' + mode.label;
  return title;
}

class QueryPanel extends Component {
  constructor(props) {
    super(props);

    this.onSegmentChange = this.onSegmentChange.bind(this);
    this.onTableTypeChange = this.onTableTypeChange.bind(this);
    this.onModeChange = this.onModeChange.bind(this);
    this.onIntervalUnitChange = this.onIntervalUnitChange.bind(this);
    this.onValuesChange = this.onValuesChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onFinish = this.onFinish.bind(this);

    this.formRef = React.createRef();

    this.tableTypeOptions = TableType.optionsForSeq();
    this.state = {
      pickerType: 'DATE',
      tableType: this.tableTypeOptions[0].value,
      modeType: 'GENERAL_CURVE',
      intervalUnit: 'MIN_UNIT',
    }
  }

  onSegmentChange(value) {
    console.log('onSegmentChange', value);
    this.setState({ pickerType: value });
  }

  onTableTypeChange(e) {
    console.log('onTableTypeChange', e);
    this.formRef.current.setFields([
      { name: 'measurement', value: [], errors: null }
    ]);
    this.setState({ tableType: e.target.value });
  }

  onModeChange(value) {
    console.log('onModeChange', value);
    this.setState({ modeType: value });
  }

  onIntervalUnitChange(value) {
    this.setState({ intervalUnit: value });
  }

  onValuesChange(changedValues, allValues) {
    console.log('onValuesChange', changedValues, allValues);
  };

  async onSubmit() {
    try {
      const values = await this.formRef.current.validateFields();

      this.onFinish(values);
    } catch (err) {
      console.log('validateFields error', err);
    }
  }

  async onFinish(values) {
    const { table_type, picker_type, mode_type, measurement } = values;

    let from, to;
    if ('date_range' in values) {
      from = values.date_range[0].startOf('day');
      to = values.date_range[1].startOf('day').add(1, 'day');
    } else {
      from = values.date.startOf('day');
      to = from.add(1, 'day');
    }

    const point_list = measurement.map(pt => pt.point_id).join(',');
    const plan = {
      point_list,
      mode_type,
      picker_type,
      table_type,
      from,
      to,
    };
    if ('data_interval' in values) {
      plan.data_interval = values.data_interval;
      plan.interval_unit = this.state.intervalUnit;
    }
    const name = getPlanName(plan, measurement);
    plan.name = name;

    console.log('open-curve', plan);
    EE.emit('open-curve', plan);
  }

  render() {
    const state = this.state;
    const { pickerType, modeType } = state;
    const formItemCss = { marginBottom: '8px' };
    const initialValues = {
      table_type: state.tableType,
      picker_type: pickerType,
      date: dayjs(),
      mode_type: state.modeType,
      data_interval: 5,
    };

    let dateItem;
    if (pickerType === 'DATE') {
      dateItem = (<Form.Item
        label="时间"
        name="date"
        style={formItemCss}
        rules={[
          {
            required: true,
          },
        ]}>
        <DatePicker style={{ width: '100%' }} />
      </Form.Item>);
    } else {
      dateItem = (<Form.Item
        label="时间"
        name="date_range"
        style={formItemCss}
        rules={[
          {
            required: true,
          },
        ]}>
        <DatePicker.RangePicker />
      </Form.Item>);
    }


    let stepItem;
    if (modeType === 'GENERAL_CURVE') {
      const selectAfter = (
        <Select
          style={{
            width: 60,
          }}
          value={state.intervalUnit}
          options={STEP_INTERVAL_OPTIONS}
          onChange={this.onIntervalUnitChange} />
      );
      stepItem = (
        <Form.Item
          label="间隔"
          name="data_interval"
          style={formItemCss}
          rules={[
            {
              required: true,
            },
          ]}>
          <InputNumber addonAfter={selectAfter} min={1} />
        </Form.Item>
      );
    }

    return (
      <div className='query-panel'>

        <Form
          className='spd-form'
          colon={false}
          requiredMark={false}
          ref={this.formRef}
          initialValues={initialValues}
          onValuesChange={this.onValuesChange}>

          <div className='query-panel-header'>
            <Form.Item
              name="table_type"
              style={formItemCss} >
              <Radio.Group optionType="button" buttonStyle="solid"
                options={this.tableTypeOptions}
                onChange={this.onTableTypeChange} />
            </Form.Item>
            <Tooltip title="查询">
              <Button
                type='primary'
                icon={<CaretRightOutlined />}
                onClick={this.onSubmit} />
            </Tooltip>
          </div>

          <Form.Item
            name="picker_type"
            style={formItemCss}>
            <Segmented
              block={true}
              options={PERIOD_OPTIONS}
              onChange={this.onSegmentChange} />
          </Form.Item>

          {dateItem}

          <Form.Item
            label="模式"
            name="mode_type"
            style={formItemCss}
            rules={[
              {
                required: true,
              },
            ]}>
            <Select options={MODE_OPTIONS} onChange={this.onModeChange} />
          </Form.Item>

          {stepItem}

          <Form.Item
            name="measurement"
            className='form-item-tree'
            style={formItemCss}
            rules={[
              {
                required: true,
                message: '请选择测量点'
              },
            ]}>
            <MeasurementTree curveApi tableType={state.tableType} />
          </Form.Item>

        </Form>
      </div>
    );
  }
}

export default QueryPanel